﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

/// <summary>
/// 第三人称视角摄像机
/// </summary>
public class ThirdControlCamera : MonoBehaviour
{
	[Header("摄像机公转的灵敏度")]
	public float sensitivity = 8;
	[Header("摄像机上下移动时，与垂直方向的最小夹角(单位：°)")]
	public float MinUpAngle = 30f;
	[Header("摄像机与主角的默认位置")]
	public Vector3 DefaultDistance = new Vector3(0, 7, -6);

	public GameObject targetMainRole;
	public CameraFollow cameraFollow;

	void Start()
	{
		Camera.main.transform.position = targetMainRole.transform.position + DefaultDistance;
		Camera.main.transform.LookAt(targetMainRole.transform.position);
	}
	void LateUpdate()
	{
		if (Input.GetMouseButton(1) == false) // 鼠标右键按下才转摄像机
		{
			return;
		}
		var xRotation = Input.GetAxis("Mouse X");
		var yRotation = Input.GetAxis("Mouse Y");

		//x方向移动，则围绕目标点做水平圆锥公转
		Camera.main.transform.RotateAround(targetMainRole.transform.position, Vector3.up, xRotation * sensitivity);
		//y方向移动，则围绕目标点做垂直方向公转
		var distance = Camera.main.transform.position - targetMainRole.transform.position;
		var angle = Vector3.Angle(distance, Vector3.up); // 取值范围0-180 当前摄像机与up方向夹角
		var deltaAngle = yRotation * sensitivity;

		float realDeltaAngle = 0;
		if (deltaAngle > 0) //仰视方向视角
		{
			realDeltaAngle = -Mathf.Min(105 - MinUpAngle - angle, Mathf.Abs(deltaAngle));
		}
		else //俯视方向视角
		{
			realDeltaAngle = Mathf.Min(angle - MinUpAngle, Mathf.Abs(deltaAngle));
		}

		var axis = Vector3.Cross(distance, Vector3.up);
		Camera.main.transform.RotateAround(targetMainRole.transform.position, axis, realDeltaAngle);

		if (cameraFollow != null)
		{
			cameraFollow.distance = Camera.main.transform.position - targetMainRole.transform.position;
            cameraFollow.UpdateCamera();
        }
	}
}